package bil.busca;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ComboBoxModel;
import javax.swing.JEditorPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML;

/**
 *
 * @author Eduardo Folly
 */
public class HTMLFormComponents {

    private JEditorPane editor;
    private List<String> lista;

    public HTMLFormComponents(JEditorPane editor) {
        this.editor = editor;
        this.lista = new ArrayList();
    }

    public List searchFormComp() {
        Document doc = editor.getDocument();
        List tags = new ArrayList();
        tags.add("input");
        tags.add("select");
        findInput(doc.getDefaultRootElement(), StyleConstants.NameAttribute, tags);
        return lista;
    }

    public List getValues() throws UnsupportedEncodingException {

        for (int x = 0; x < lista.size(); x++) {
            String obj = lista.get(x);

            String valor = getStringValue(obj);
            valor = URLEncoder.encode(valor, "UTF-8");
            if (valor.isEmpty()) {
                lista.remove(x);
                x--;
            } else {
                lista.set(x, obj + "=" + valor);
            }
        }

        return lista;
    }

    private Element findInput(Element e,
            Object attr,
            List value) {

        if (e == null) {
            return null;
        }

        String myValue = e.getAttributes().getAttribute(attr).toString();
        if (value.indexOf(myValue) >= 0) {
            String nome = e.getAttributes().getAttribute(HTML.Attribute.NAME).toString();

            if (lista.indexOf(nome) < 0) {
                lista.add(nome);
            }
        }

        for (int i = 0, n = e.getElementCount(); i < n; ++i) {
            Element found = findInput(e.getElement(i), attr, value);
            if (found != null) {
                return found;
            }
        }

        return null;
    }

    public String getStringValue(String name) {
        Object model = getFieldModel(name);
        if (model == null) {
            throw new IllegalArgumentException("Campo inexistente '" + name + "'");
        }

        if (model instanceof Document) {
            Document field = (Document) model;
            try {
                return field.getText(0, field.getLength());
            } catch (BadLocationException e) {
                throw new RuntimeException(e.getMessage());
            }
        } else if (model instanceof ComboBoxModel) {
            ComboBoxModel items = (ComboBoxModel) model;
            Object item = items.getSelectedItem();
            if (item == null) {
                return "";
            } else {
                String conteudo = item.toString();

                String teste = editor.getText();

                int t = teste.indexOf("name=\"" + name + "\"");

                teste = teste.substring(t);

                t = teste.indexOf("</select>");

                teste = teste.replaceAll("selected", "");

                teste = teste.substring(0, t);

                teste = teste.replace("\n", "");

                StringBuilder sb = new StringBuilder();
                char velho = ' ';
                for (int x = 0; x < teste.length(); x++) {
                    char novo = teste.charAt(x);
                    if (novo != ' ') {
                        sb.append(novo);
                    } else {
                        if (velho != ' ') {
                            sb.append(novo);
                        }
                    }
                    velho = novo;
                }

                teste = sb.toString();
                t = teste.indexOf(conteudo) - 1;

                teste = teste.substring(0, t);

                t = teste.lastIndexOf("value=") + 6;

                teste = teste.substring(t).trim();

                teste = teste.replace("\"", "");
                teste = teste.replace("'", "");

                return teste;
            }

            /*
            // mostrar !!
            AttributeSet set = e.getAttributes();

            System.out.println("--");

            for (Enumeration en = set.getAttributeNames(); en.hasMoreElements();) {
            Object att = en.nextElement();
            System.out.println(att.toString());
            System.out.println(e.getAttributes().getAttribute(att).toString());
            }
            System.out.println();
            //--

             */
        } else {
            throw new ClassCastException("Campo '" + name + "' mao possui um model reconhecido: " + model.getClass());
        }
    }


    /*
    public void setStringValue(String name, String value) {
    Object model = getFieldModel(name);
    if (model == null) {
    throw new IllegalArgumentException("no field named '" + name + "'");
    }

    // Replace old contents with value
    if (model instanceof Document) {
    // for INPUT type=text and TEXTAREA
    Document field = (Document) model;
    try {
    field.remove(0, field.getLength());
    } catch (BadLocationException e) {
    }

    try {
    field.insertString(0, value, null);
    } catch (BadLocationException e) {
    }
    } else if (model instanceof ComboBoxModel) {
    ComboBoxModel items = (ComboBoxModel) model;
    found:
    {
    for (int i = 0, n = items.getSize(); i < n; ++i) {
    Object item = items.getElementAt(i);
    if (item != null && item.toString().equals(value)) {
    items.setSelectedItem(item);
    break found;
    }
    }
    throw new IllegalArgumentException("field '" + name + "' doesn't contain an option '" + value + "'");
    }
    } else {
    throw new ClassCastException("field '" + name + "' is not a string");
    }
    }

    public boolean getBooleanValue(String name) {
    Object model = getFieldModel(name);
    if (model == null) {
    throw new IllegalArgumentException("no field named '" + name + "'");
    }

    if (model instanceof ButtonModel) // for INPUT=checkbox | radio
    {
    return ((ButtonModel) model).isSelected();
    } else {
    throw new ClassCastException("field '" + name + "' is not a boolean");
    }
    }

    public void setBooleanValue(String name, boolean value) {
    Object model = getFieldModel(name);
    if (model == null) {
    throw new IllegalArgumentException("no field named '" + name + "'");
    }

    // Replace old contents with value
    if (model instanceof ButtonModel) {
    ((ButtonModel) model).setSelected(value);
    } else {
    throw new ClassCastException("field '" + name + "' is not a boolean");
    }
    }
     */
    public Object getFieldModel(String name) {
        Document doc = editor.getDocument();

        Element e = findElement(doc.getDefaultRootElement(),
                HTML.Attribute.NAME, name);
        if (e == null) {
            return null;
        }
        Object model = e.getAttributes().getAttribute(StyleConstants.ModelAttribute);
        return model;
    }

    private Element findElement(Element e,
            HTML.Attribute attr,
            String value) {
        if (e == null) {
            return null;
        }

        String myValue = (String) e.getAttributes().getAttribute(attr);
        if (value.equals(myValue)) {
            return e;
        }

        // Search through children
        for (int i = 0, n = e.getElementCount(); i < n; ++i) {
            Element found = findElement(e.getElement(i), attr, value);
            if (found != null) {
                return found;
            }
        }

        return null;
    }
}
